package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;

import java.io.IOException;

public class ROAD {
    private byte[] dataCode = null;
    private SubSeqOfOads oads = null;
    private OAD oad = null;

    public ROAD() {
    }

    public byte[] getDataCode() {
        return dataCode;
    }

    public SubSeqOfOads getOads() {
        return oads;
    }

    public OAD getOad() {
        return oad;
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(OAD oad, SubSeqOfOads oads) {
        this.oad = oad;
        this.oads = oads;
    }

    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.oad = new OAD();
        codeLength += this.oad.decode(input);
        this.oads = new SubSeqOfOads();
        codeLength += this.oads.decode(input);
        return codeLength;
    }

    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength = 0;
        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (int i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if (this.oads != null && this.oad != null) {
                codeLength += this.oads.encode(output);
                codeLength += this.oad.encode(output);
            } else {
                throw new RuntimeException("oads || oad is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.toByteArray();
    }

    @Override
    public String toString() {
        if (this.oad != null && this.oads != null) {
            return "sequence: {" + "oad: " + this.oad + ", oads: " + this.oads + "}";
        } else {
            return "oads || oad is null";
        }
    }
}



